/*
 * Copyright 2011 David de Mingo
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package org.shalma.internal;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.xml.bind.JAXBContext;

public class ModuleRegistry {

	private List<Module> modules;

	public static ModuleRegistry getInstance() {
		return ModuleRegistryHolder.instance;
	}

	private static class ModuleRegistryHolder {
		private static final ModuleRegistry instance = new ModuleRegistry();
	}

	private ModuleRegistry() {
	}

	public synchronized List<Module> getModules() {

		if (modules != null)
			return modules;

		modules = new ArrayList<Module>();

		final JAXBContext context;
		final Enumeration<URL> urls;

		try {

			context = JAXBContext.newInstance(Module.class);
			urls = Thread.currentThread().getContextClassLoader()
					.getResources("module.xml");

		} catch (Exception e) {
			throw new RuntimeException("Init ModuleRegistry", e);
		}

		while (urls.hasMoreElements()) {

			URL url = urls.nextElement();

			try {

				InputStream inputStream = null;

				try {

					inputStream = url.openStream();

					final Module module = (Module) context.createUnmarshaller()
							.unmarshal(inputStream);
					module.update(url);

					modules.add(module);

				} finally {
					try {
						if (inputStream != null)
							inputStream.close();
					} catch (IOException ignore) {
					}
				}
			} catch (Exception e) {

				// log!!!
				e.printStackTrace();
			}
		}

		return modules;
	}
}
